# -*- coding=utf-8 -*-
# @Time : 2019/7/13
# @Author : rubick


import hashlib
import requests
from lxml import html


''' 登录密码加密 '''
def getEncryptPwd(pwd, verfify):
    m2 = hashlib.md5()
    m2.update(pwd.encode('utf-8'))
    m2_sec = m2.hexdigest()

    append_str = m2_sec + verfify
    m3 = hashlib.md5()
    m3.update(append_str.encode('utf-8'))
    m3_sec = m3.hexdigest()
    return m3_sec

''' header '''
headers = {
    'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Safari/605.1.15',
    'cookie':'device=desktop; lang=zh-cn; theme=default; windowHeight=738; windowWidth=1248;',
    'accept-language':'zh-cn'
}
'''cookie'''
cookies = {}

# Home page 更新Header 设置zentaosid
home_url = 'https://project.youtil.cn/'
home_page = requests.get(home_url, headers=headers)
for k, v in home_page.cookies.items():
    if k == 'zentaosid':
        header_cookies = headers['cookie']
        header_cookies = header_cookies + ' '+k+'='+v
        headers['cookie'] = header_cookies
    cookies[k] = v
print(headers)

# 登录 page 获取verifyRand
login_url = 'https://project.youtil.cn/index.php?m=user&f=login&referer=Lw=='
login_page = requests.get(login_url, headers=headers)
login_page.encoding = 'utf-8'
login_tree = html.fromstring(login_page.text)
verifyRand = login_tree.xpath('//form//input[@id="verifyRand"]')
if verifyRand:
    verifyRand = verifyRand[0].attrib['value']

print(verifyRand)

# 登录用户
password = getEncryptPwd('Rubick123', verifyRand)
print(password)
param_login = {
    'account': 'rubick',
    'password': password,
    'verifyRand': verifyRand
}
login_result = requests.post(login_url, data=param_login, headers=headers)
login_result.encoding = 'utf-8'
print(login_result.text)
print(login_result.cookies)
print(login_result.headers)

# 首页
my_home_page_url = 'https://project.youtil.cn/index.php?m=my&f=index'
my_home_page_res = requests.get(my_home_page_url, headers=headers)
my_home_page_res.encoding = 'utf-8'
print(my_home_page_res.text)
print(my_home_page_res.headers)


